package org.linphone.sub.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;

import com.zhy.http.okhttp.BuildConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.linphone.app.MyApplication;
import org.linphone.utils.SpUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Xiang on 2019/1/26.
 */
public class UpdateUtil {

	private int mCurrentVersion;
	//private int mNewVersion;
	private AppCompatActivity mActivity;
	private String mDownloadUrl = "";
	private OnUpdateListener mOnUpdateListener;
	public UpdateUtil(AppCompatActivity appCompatActivity){
		mActivity = appCompatActivity;
		getCurrentVersion();
	}

	private void getCurrentVersion() {
		try {
			PackageManager packageManager = MyApplication.getContext().getPackageManager();
			PackageInfo packInfo = packageManager.getPackageInfo(MyApplication.getContext().getPackageName(), 0);
			mCurrentVersion = packInfo.versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public interface OnUpdateListener{
		void onUpdate();
	}

	public void setmOnUpdateListener(OnUpdateListener onUpdateListener){
		mOnUpdateListener = onUpdateListener;
	}

	public void checkVersion(){
		String ip = SpUtil.getString(MyApplication.getContext(),"updateIP", "");
		OkHttpUtils.get()
				// 服务器json地址（json文件或者接口）
				.url("http://"+ip+"/phone/phone.txt")
				.build()
				.execute(new StringCallback() {
					@Override
					public void onError(Call call, Exception e, int id) {

					}

					@Override
					public void onResponse(String response, int id) {
						//本地APP versionCode
						int versionCode = BuildConfig.VERSION_CODE;
						Log.i("1223", "onResponse: -----------"+mCurrentVersion);
						try {
							JSONObject jsonObject = new JSONObject(response);
							// 服务器端APP versionCode
							int vesion = Integer.valueOf(jsonObject.optString("new_version").trim());
							Log.i("1223", "onResponse: +++++++++++++"+vesion);
							//app大小
							String size = jsonObject.optString("target_size");
							//更新日志
							String log = jsonObject.optString("update_log");
							mDownloadUrl = jsonObject.optString("update_url");
							//本地版本小于服务器版本显示更新对话框
							if (mCurrentVersion < vesion) {
								showDiyDialog(size, log);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	private void showDiyDialog(String targetSize, String updateLog) {
		String msg = "";
		if (!TextUtils.isEmpty(targetSize)) {
			msg = "新版本：" + targetSize + "\n\n";
		}

		if (!TextUtils.isEmpty(updateLog)) {
			msg += updateLog;
		}
		new AlertDialog.Builder(mActivity)
				.setTitle(String.format("升级到最新版本!"))
				.setMessage(msg)
				.setPositiveButton("升级", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						downloadApk();
						dialog.dismiss();
					}
				})
				.create()
				.show();
	}

	private void downloadApk() {
		//显示下载进度
		ProgressDialog dialog = new ProgressDialog(mActivity);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setCancelable(false);
		dialog.show();
		new Thread(new DownloadApk(dialog)).start();
	}

	private class DownloadApk implements Runnable {
		private ProgressDialog dialog;
		InputStream is;
		FileOutputStream fos;

		public DownloadApk(ProgressDialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void run() {
			OkHttpClient client = new OkHttpClient();
			//下载地址
			Request request = new Request.Builder().get().url(mDownloadUrl).build();
			try {
				Response response = client.newCall(request).execute();
				if (response.isSuccessful()) {
					//获取内容总长度
					long contentLength = response.body().contentLength();
					//设置最大值
					dialog.setMax((int) contentLength);
					//保存到sd卡
					File apkFile = new File("mnt/sdcard", "phone.apk");
					fos = new FileOutputStream(apkFile);
					//获得输入流
					is = response.body().byteStream();
					//定义缓冲区大小
					byte[] bys = new byte[1024];
					int progress = 0;
					int len = -1;
					while ((len = is.read(bys)) != -1) {
						try {
							Thread.sleep(1);
							fos.write(bys, 0, len);
							fos.flush();
							progress += len;
							//设置进度
							dialog.setProgress(progress);
						} catch (InterruptedException e) {

						}
					}
					//下载完成,提示用户安装
					installApk(apkFile);
				}
			} catch (IOException e) {

			} finally {
				//关闭io流
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					is = null;
				}
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					fos = null;
				}
			}
			dialog.dismiss();
		}
	}

	private void installApk(File file) {
		//调用系统安装程序
		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		mActivity.startActivity(intent);
		if(mOnUpdateListener!=null){
			mOnUpdateListener.onUpdate();
		}
	}


}
